package com.edu.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

/**
 * @Author:何包蛋
 * @Date :2022/12/7 - 12 - 07 - 15:29
 */

@Controller
public class DownLoadController {

    @RequestMapping("/download01")
    public void downLoad(HttpServletRequest request , HttpServletResponse response) throws IOException {

        /*
         *       获取 Web目录下 文件的真实路径
         *       1  request.getRealPath 不推荐已经过时。
         *       2  request.getServletContext().getRealPath("") Servlet API 3.0+
         *       3  request.getSession().getServletContext().getRealPath();
         * */
        String realPath = request.getSession().getServletContext().getRealPath("/imgs/2544.webp");
        File file = new File(realPath);
        String name = file.getName();
        /*
         *   setHeader 设置响应头
         *
         * */
        response.setHeader("content-disposition","attachment;filename="+ URLEncoder.encode(name,"UTF-8"));
        InputStream ins = new FileInputStream(realPath);
        OutputStream oos = response.getOutputStream();
//        int a = 0;
//        while( (a = ins.read())!= -1){
//            oos.write(a);
//        }
        byte[] bytes = new byte[512];
        int a = 0;
        while((a = ins.read(bytes)) != -1){
            oos.write(bytes,0,a);
        }
        oos.close();
        ins.close();

    }

    @RequestMapping("/download02")
    public void downLoad02(HttpServletResponse response,String url) throws IOException {

        String realPath = "E:\\"+url;
        File file = new File(realPath);
        System.out.println("2:"+file);
        String name = file.getName();
        /*
         *   setHeader 设置响应头
         *
         * */
        response.setHeader("content-disposition","attachment;filename="+ URLEncoder.encode(name,"UTF-8"));
        InputStream ins = new FileInputStream(realPath);
        OutputStream oos = response.getOutputStream();
//        int a = 0;
//        while( (a = ins.read())!= -1){
//            oos.write(a);
//        }
        byte[] bytes = new byte[512];
        int a = 0;
        while((a = ins.read(bytes)) != -1){
            oos.write(bytes,0,a);
        }
        oos.close();
        ins.close();

    }
}
